package com.zm.demo.core.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import static java.lang.System.out;

/**
 * @author zoum
 * @create 2019/6/18 18:31
 */
public class ExecutorCompletionServiceDemo {

    public static void main(String[] args){
        ExecutorService pool = Executors.newFixedThreadPool(100);
        List<Future<Integer>> fs = new ArrayList<>();
        ExecutorCompletionService ecs = new ExecutorCompletionService(pool);
        for (int i = 0; i< 100; i++){
            final int j = i;
            fs.add(ecs.submit(() -> {
                Thread.sleep(new Random().nextInt(1000));
                return j;
            }));
        }
        try {

            Future<Integer> f = ecs.take();

            out.println("solve is " + f.get() + " " + f.isDone());
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            for (int i = 0; i < fs.size(); i++) {
                fs.get(i).cancel(true);
            }
        }

        for (int i = 0; i < fs.size(); i++) {
            out.println(i + ": " + fs.get(i).isCancelled());
        }

        pool.shutdownNow();


    }
}
